package controllers

import (
	"encoding/json"
	"errors"
	"gitee.com/lzqysoft/ims/models"
	"strings"

	"github.com/astaxie/beego"
	"strconv"
)

// ImsProjectFlowController operations for ImsProjectFlow
type ImsProjectFlowController struct {
	CommonController
}

// URLMapping ...
func (c *ImsProjectFlowController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
	c.Mapping("QueryFlowData", c.QueryFlowData)
	c.Mapping("Approve", c.Approve)
	c.Mapping("QueryProjectFLow", c.QueryProjectFLow)
	c.Mapping("QueryBusyFlowing", c.QueryBusyFlowing)
	c.Mapping("ProjectApprove2CheckOrFinish", c.ProjectApprove2CheckOrFinish)
	c.Mapping("QueryBusyDoing", c.QueryBusyDoing)
	c.Mapping("StartProjectChangeFlow", c.StartProjectChangeFlow)

}

// Post ...
// @Title Post
// @Description create ImsProjectFlow
// @Param	body		body 	models.ImsProjectFlow	true		"body for ImsProjectFlow content"
// @Success 201 {int} models.ImsProjectFlow
// @Failure 403 body is empty
// @router / [post]
func (c *ImsProjectFlowController) Post() {
	beego.Debug("Post")
	var v models.ImsProjectFlow
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		if _, err := models.AddImsProjectFlow(&v); err == nil {
			c.Ctx.Output.SetStatus(201)
			c.Data["json"] = v
		} else {
			c.Data["json"] = err.Error()
		}
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// GetOne ...
// @Title Get One
// @Description get ImsProjectFlow by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.ImsProjectFlow
// @Failure 403 :id is empty
// @router /:id [get]
func (c *ImsProjectFlowController) GetOne() {
	idStr := c.Ctx.Input.Param(":id")
	//id, _ := strconv.Atoi(idStr)
	v, err := models.GetImsProjectFlowById(idStr)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = v
	}
	c.ServeJSON()
}

// GetAll ...
// @Title Get All
// @Description get ImsProjectFlow
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.ImsProjectFlow
// @Failure 403
// @router / [get]
func (c *ImsProjectFlowController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	var limit int64 = 10
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, err := models.GetAllImsProjectFlow(query, fields, sortby, order, offset, limit)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = l
	}
	c.ServeJSON()
}

// Put ...
// @Title Put
// @Description update the ImsProjectFlow
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.ImsProjectFlow	true		"body for ImsProjectFlow content"
// @Success 200 {object} models.ImsProjectFlow
// @Failure 403 :id is not int
// @router /:id [put]
func (c *ImsProjectFlowController) Put() {
	idStr := c.Ctx.Input.Param(":id")
	//id, _ := strconv.Atoi(idStr)
	v := models.ImsProjectFlow{Id: idStr}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		if err := models.UpdateImsProjectFlowById(&v); err == nil {
			c.Data["json"] = "OK"
		} else {
			c.Data["json"] = err.Error()
		}
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// Delete ...
// @Title Delete
// @Description delete the ImsProjectFlow
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /:id [delete]
func (c *ImsProjectFlowController) Delete() {
	idStr := c.Ctx.Input.Param(":id")
	//id, _ := strconv.Atoi(idStr)
	if err := models.DeleteImsProjectFlow(idStr); err == nil {
		c.Data["json"] = "OK"
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// QueryFlowData ...
// @Title QueryFlowData
// @Description QueryFlowData
// @Param	QueryParams  path 	QueryParams	 true		"QueryParams"
// @Success 200 {map[string]interface}  query success
// @Failure 403  empty
// @router /QueryFlowData [post]
func (c *ImsProjectFlowController) QueryFlowData() {
	user := c.User
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var params QueryParams
	if err = json.Unmarshal(tdata, &params); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	projectFlow, ok := params.Query["projectFlow"]
	if !ok {
		beego.Debug("projectFlow 参数传递错误！")
		c.RetError(ErrInputData)
	}

	if !ok {
		beego.Debug("projectFlow 参数传递错误！")
		c.RetError(ErrInputData)
	}
	ftype, ok := params.Query["type"]
	if !ok {
		beego.Debug("type 参数传递错误！")
		c.RetError(ErrInputData)
	}
	itype, err := strconv.Atoi(ftype)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	bname, ok := params.Query["bname"]
	if !ok {
		beego.Debug("bname 参数传递错误！")
		c.RetError(ErrInputData)
	}
	//bid, ok  := params.Query["bid"]
	//if !ok {
	//	beego.Debug("bid 参数传递错误！")
	//	c.RetError(ErrInputData)
	//}
	beego.Debug("----------------------Ftype:", ftype)
	res, err := models.GetImsProjectsData(projectFlow, itype, user, bname)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(res)
}

// Approve ...
// @Title Approve
// @Description Approve
// @Param	TransitionInstance  path 	TransitionInstance	 true		"TransitionInstance"
// @Success 200 {map[string]interface}  query success
// @Failure 403  empty
// @router /Approve [post]
func (c *ImsProjectFlowController) Approve() {
	user := c.User
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var t models.TransitionInstance
	if err = json.Unmarshal(tdata, &t); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	if err := models.FlowApprove(&t, user); err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(nil)
}

// QueryProjectFLow ...
// @Title QueryProjectFLow
// @Description QueryProjectFLow
// @Param	QueryProjectFLow  path 	QueryProjectFLow	 true		"TransitionInstance"
// @Success 200 {map[string]interface}  query success
// @Failure 403  empty
// @router /QueryProjectFLow [post]
func (c *ImsProjectFlowController) QueryProjectFLow() {
	user := c.User
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var params QueryParams
	if err = json.Unmarshal(tdata, &params); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	ptype, ok := params.Query["type"]
	if !ok {
		beego.Debug("ptype")
		c.RetError(ErrInputData)
	}
	status, ok := params.Query["status"]
	if !ok {
		beego.Debug("result")
		c.RetError(ErrInputData)
	}
	istatus, _ := strconv.Atoi(status)
	//result, ok := params.Query["result"]
	if !ok {
		beego.Debug("result")
		c.RetError(ErrInputData)
	}
	itype, _ := strconv.Atoi(ptype)

	l, err := models.GetImsProjectByTypeUserAndRole(itype, istatus, user)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(l)
}

// QueryBusyFlowing ...
// @Title QueryBusyFlowing
// @Description QueryBusyFlowing
// @Param	QueryBusyFlowing  path 	QueryBusyFlowing	 true		"QueryBusyFlowing"
// @Success 200 {map[string]interface}  query success
// @Failure 403  empty
// @router /QueryBusyFlowing [post]
func (c *ImsProjectFlowController) QueryBusyFlowing() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	busyName := sdata["busyName"].(string)
	ptype := sdata["type"].(string)
	itype, err := strconv.Atoi(ptype)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	v, err := models.GetBusyFlowingByType(user, busyName, itype)
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}

// ProjectApprove2CheckOrFinish ...
// @Title ProjectApprove2CheckOrFinish
// @Description 提交项目， type ： 0 项目申报， 1 项目中期检查 2 结项
// @Param	ProjectApprove2CheckOrFinish  path 	ProjectApprove2CheckOrFinish	 true		"ProjectApprove2CheckOrFinish"
// @Success 200 {map[string]interface}  approve success
// @Failure 403  empty
// @router /ProjectApprove2CheckOrFinish [post]
func (c *ImsProjectFlowController) ProjectApprove2CheckOrFinish() {
	user := c.User
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var params QueryParams
	if err = json.Unmarshal(tdata, &params); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	ptype, ok := params.Query["type"]
	if !ok {
		beego.Debug("ptype")
		c.RetError(ErrInputData)
	}
	project, ok := params.Query["project"]
	if !ok {
		beego.Debug("project")
		c.RetError(ErrInputData)
	}
	itype, _ := strconv.Atoi(ptype)
	// 生成 projecte_flow
	m, err := models.GetImsProjectById(project)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	if err = models.StartImsProjectFlow(*m, itype, user); err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(nil)
}

// StartProjectChangeFlow ...
// @Title StartProjectChangeFlow
// @Description 提交项目， type ： 0 项目申报， 1 项目中期检查 2 结项
// @Param	StartProjectChangeFlow  path 	ProjectApprove2CheckOrFinish	 true		"ProjectApprove2CheckOrFinish"
// @Success 200 {map[string]interface}  approve success
// @Failure 403  empty
// @router /StartProjectChangeFlow [post]
func (c *ImsProjectFlowController) StartProjectChangeFlow() {
	user := c.User
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var m models.ImsProject
	if err = json.Unmarshal(tdata, &m); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	beego.Debug(m.Content)
	if err = models.StartImsProjectFlow(m, 3, user); err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(nil)

}

// QueryBusyDoing ...
// @Title QueryBusyDoing
// @Description 查询需要审批的业务， type ： 0 项目申报， 1 项目中期检查 2 结项
// @Param	QueryBusyDoing  path 	QueryBusyDoing	 true		"QueryBusyDoing"
// @Success 200 {map[string]interface}  query success
// @Failure 403  empty
// @router /QueryBusyDoing [post]
func (c *ImsProjectFlowController) QueryBusyDoing() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	busyName := sdata["busyName"].(string)
	ptype := sdata["type"].(string)
	itype, err := strconv.Atoi(ptype)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	v, err := models.GetBusyDoingByType(user, busyName, itype)
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}
